import requests
from bs4 import BeautifulSoup
import jieba.posseg as pseg
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 笔趣阁
url = "https://www.biquke.vip/book/209/139997.html"

# 获取HTML文本
r = requests.get(url, timeout=30)
r.raise_for_status()  # 如果状态不是200，引发异常
r.encoding = 'utf-8'  # 无论原来用什么编码，都改成utf-8
html_text = r.text

# 提取小说内容
soup = BeautifulSoup(html_text, 'lxml')
novel_text = soup.find('div', id='content').text
novel_text = novel_text.replace(' ', '').replace('\n\n', '').replace('\r\n', '')

# 提取人物姓名
words = pseg.cut(novel_text)
person_names = [word.word for word in words if word.flag == 'nr' and len(word.word) > 1]

# 统计人物姓名次数，获取前10个出现次数最多的人物姓名
character_counts = Counter(person_names)
data = character_counts.most_common(10)
word_freq = {item[0]: item[1] for item in data}

# 输出前10人物次数
for name, count in word_freq.items():
    print(f"人物姓名：{name}，出现次数：{count}")
# 创建WordCloud对象并生成词云图
wordcloud = WordCloud(font_path="msyh.ttc", width=800, height=400, background_color="white")
wordcloud.generate_from_frequencies(word_freq)

# 展示词云图
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()